package cn.lcc.utils.handler;

import cn.lcc.utils.core.NettyServer;
import cn.lcc.utils.core.config.NettyConfig;
import cn.lcc.utils.handler.ecoder.WatchDecoder;
import cn.lcc.utils.handler.ecoder.WatchEncoder;
import cn.lcc.utils.watch.WatchHeader;
import hy.iot.core.support.IotFieldConfig;
import hy.iot.core.support.IotFieldTranseSupport;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * NettyServerImpl类是Netty服务器的实现，用于处理网络通信。
 *
 * @author 21341
 */
@Slf4j
@Component("WatchNettyServer")
@AllArgsConstructor
public class WatchNettyServer implements NettyServer {

    // 静态变量，用于保存服务器的Channel和EventLoopGroup实例
    private static Channel serverChannel;
    private static EventLoopGroup masterGroup;
    private static EventLoopGroup slaveGroup;
    private NettyConfig watchNettyConfig;
    /**
     * 启动Netty服务器的方法。
     *
     * @return 如果服务器已经启动，则返回true；否则返回false。
     */
    @Override
    public boolean start() {

        // 检查服务器是否已经启动
        if (serverChannel != null) {
            return serverChannel.isActive();
        }

        // 创建主从两个EventLoopGroup，用于处理连接和IO事件
        masterGroup = new NioEventLoopGroup(watchNettyConfig.getMasterSize());
        slaveGroup = new NioEventLoopGroup(watchNettyConfig.getSlaveSize());
        IotFieldTranseSupport iotsup = getIotSup();
        // 创建ServerBootstrap，配置服务器参数
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(masterGroup, slaveGroup).channel(NioServerSocketChannel.class)
                // 配置ChannelInitializer，用于初始化新的连接的ChannelPipeline
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        // 添加编码器、解码器和会话处理器到ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new ReadTimeoutHandler(2*60));
                        pipeline.addLast(new WatchEncoder());
                        pipeline.addLast(new WatchDecoder());
                        // 添加IdleStateHandler，设置读写超时
                        pipeline.addLast(new IdleStateHandler(2*60, 0, 0));
//                            pipeline.addLast(new IdleStateHandler(60 * 5, 0, 0));
                        pipeline.addLast( new WatchSessionHandler(iotsup));

                    }
                })
                // 配置TCP_NODELAY选项，控制是否启用Nagle算法
                .childOption(ChannelOption.TCP_NODELAY, watchNettyConfig.getTcpNoDelay())
                // 配置SO_KEEPALIVE选项，保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, watchNettyConfig.getKeepAlive());
        serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        // 绑定端口，获取ChannelFuture
        ChannelFuture channelFuture = serverBootstrap.bind(watchNettyConfig.getPort());
        // 获取服务器的Channel实例
        serverChannel = channelFuture.channel();
        log.info("启动netty,接受手表协议 端口 port: {}",watchNettyConfig.getPort());
        // 返回启动成功
        return true;
    }

    private IotFieldTranseSupport getIotSup() {
        IotFieldTranseSupport support = new IotFieldTranseSupport(new IotFieldConfig(
                WatchHeader.class,"cn.lcc.utils.watch",
                null,"cn.lcc.utils.endpoint","watch"
        ));
       return support;
    }

    /**
     * 停止Netty服务器的方法。
     *
     * @return 停止成功返回true，否则返回false。
     */
    @Override
    public boolean stop() {
        // 关闭服务器Channel
        serverChannel.close();
        // 关闭主EventLoopGroup
        if (masterGroup != null) {
            masterGroup.shutdownGracefully();
        }
        // 关闭从EventLoopGroup
        if (slaveGroup != null) {
            slaveGroup.shutdownGracefully();
        }
        // 返回停止成功
        return true;
    }


}
